/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package comunicacao;

import entities.Server;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.logging.Level;
import java.util.logging.Logger;
import main.ConfigGeral;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

/**
 *
 * @author Leonardo Lino
 */
public class GestorZooKeeper {

    private ZooKeeper zk;

    public GestorZooKeeper() {

        try {
            connect(ConfigGeral.CG_ZOOKEEP_IP + ":" + ConfigGeral.CG_ZOOKEEP_PORT, 455);

        } catch (IOException ex) {
            System.err.println(ex.toString());
        } catch (InterruptedException ex) {
            System.err.println(ex.toString());
        }
    }

    private ZooKeeper connect(String hosts, int timeout)
            throws IOException, InterruptedException {

        final CountDownLatch signal = new CountDownLatch(1);

        zk = new ZooKeeper(hosts, timeout, null);
        return zk;
    }

    public ArrayList<Server> getAppServers() {
        ArrayList<Server> appServers = null;
        try {
            appServers = new ArrayList<Server>();

            List<String> lista = zk.getChildren("/AppServers", null);
            for (String nodeName : lista) {

                Stat stat = zk.exists("/AppServers/" + nodeName, null);
                byte[] dataByte = zk.getData("/AppServers/" + nodeName, null, stat);

                String dataStr = new String(dataByte);

                String[] piece = dataStr.split(":");
                Server server = new Server(piece[0], Integer.parseInt(piece[1]));
                server.setNodeName(nodeName);
                appServers.add(server);
            }

        } catch (KeeperException ex) {
            Logger.getLogger(GestorZooKeeper.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InterruptedException ex) {
            Logger.getLogger(GestorZooKeeper.class.getName()).log(Level.SEVERE, null, ex);
        }

        return appServers;
    }

}
